<?php

namespace app\api\service;

use app\common\model\Product;

class ProductService
{
    /*** 产品列表
     * @param $page int 页码
     * @param $num int 个数
    */
    public static function productList($page,$num,$key,$class_one,$price_sort,$commission_sort){
        $where[] = ["enable","=",1];
        if(!empty($key)){
            $where[] = ["p_num|p_name","like","%.$key.%"];
        }
        if(!empty($class_one)){
            $where[] = ["class_one","=",1];
        }
        $orderBy = "id desc";
        if(!empty($price_sort)){
            if($price_sort == 1){
                $orderBy = "supply_price asc";
            }elseif($price_sort == 2){
                $orderBy = "supply_price desc";
            }
        }
        if(!empty($commission_sort)){
            if($commission_sort == 1){
                $orderBy = "commission_price,commission_rate asc";
            }elseif($commission_sort == 2){
                $orderBy = "commission_price,commission_rate desc";
            }
        }
        $p_field = "id,p_num,p_name,img,img_json,supply_price,commission_rate,commission_price";
        $data = Product::dataList($where,$page,$num,$p_field,$orderBy);
        if(!empty($data)){
            $data = $data->toArray();
            foreach ($data as $k => $v){
                $data[$k]["img_json"] = !empty($v["img_json"])?json_decode($v["img_json"]):"";
            }
            $count= Product::dataCount($where);
        }else{
            $data = [];
            $count = 0;
        }
        return [$data,$count];
    }

    public static function productDetailed($id){
        $info = [];
        $data = Product::dataInfo(["id"=>$id]);
        $info = $data;
        $info["img_json"] = !empty($info["img_json"])?json_decode($info["img_json"]):"";
        return $info;
    }
}